import {strFrom, strTo} from './str.js'

const number = (a) => {
  var r = typeof a === 'string' ? parseFloat(a.replace(/[^\d\.-]|\b-/g, '')) : +a
  return isNaN(r) ? 0 : r
}
// 判断是否数字
const isNumber = (a) => a != null && !isNaN(a)

// 如果 a 的大小在 b 和 c 之间，则返回 a。否则返回 b 或 c
const numRange = function(a, b, c) {
	return a == null ? ((b || b === 0) ? b : (c || c === 0) ? c : a) : ((b || b === 0) && a < b) ? b : ((c || c === 0) && a > c) ? c : a
}
// js小数相加运算出现多位小数的解决办法
const numAdd = function(...args) {
  let m = 0
  let r = 0
  args.forEach(a => {
    m = Math.max(m, strFrom(a + '', '.').length)
    r += a
  })
  m = Math.pow(10, m)
	return Math.round(r * m) / m
}
// 给数字加上分隔符  /@a -> str, b -> length?, c -> separator?, d -> rightward?
const numFormat = function(a, b, c, d) {
	a = String(a);
	b == null && (b = 3);
	c == null && (c = ',');
	let e = a.replace(/[^.\d]/g, '').split('.'), s = e[0], l = s.length, i = d ? 0 : l, t = '', n = a.charAt(0) === '-' ? '-' : '';
	if (d) {
		do {
			i += b;
			t += (i < l ? s.substr(i - b, b) + c : s.substr(i - b));
		} while (i < l);
	} else {
		do {
			i -= b;
			t = (i > 0 ? c + s.substr(i, b) : s.substr(0, b + i)) + t;
		} while (i > 0);
	}
	return n + t + (e.length > 1 ? '.' + strFrom(a, '.').replace(RegExp('[.' + c + ']', 'g'), '') : '');
}
// 调整小数位数
const numDecimal = function(a, b) {
	if (!b) {
		return a;
	} else if (b < 0) {
		return a;
	} else {
		var f = strFrom('' + a, '.');
		return f ? strTo('' + a, '.') + '.' + f.slice(0, b) : a
	}
}

export {number, isNumber, numRange, numAdd, numFormat, numDecimal}